var util = require('../../libs/util.js');
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
var app = getApp()
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    appName: app.appName,
    hasData: false,
    isAdmin: false,
    userInfo: {},
    truename: "",
    dbtn_type: 'all',
    searchShowed: false,
    searchVal: "",
    selected: false,
    delivery_date: '',
    delivery_date_selected: false,
    sql_noPackage: false,
    sql_noClose: false,
    sql_noWarehouse: false,
    sql_delivery_date_start: '',
    sql_delivery_date_end: '',
    sql_warehouse: '',
    dialog: false,
    onePriceTypeOfPay: true,
    tab: 2,
    modalName: '',
    currentDelivery: [],
    pageSize: 10,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true,
    listSort: 'DESC',
    sortText: '倒序',
    closeDeliveryBtn: false,
    isCloseRole: false
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  // onPullDownRefresh: function () {
  //   wx.showToast({
  //     title: '加载中...',
  //     icon: 'loading'
  //   })
  //   this.loadData();
  //   console.log('onPullDownRefresh', new Date())
  // },
  // stopPullDownRefresh: function () {
  //   wx.stopPullDownRefresh({
  //     complete: function (res) {
  //       wx.hideToast()
  //       console.log(res, new Date())
  //     }
  //   })
  // },
  onShow: function (e) {
    var that = this;
    wx.getStorage({
      key: 'path_warehouse',
      success: function (res) {
        if (res.data) {
          wx.setStorageSync('warehouse', {
            id: res.data.value,
            name: res.data.name
          });
          that.setData({
            sql_warehouse: res.data.value
          })
          that.loadData();
        }
      }
    });
  },
  onLoad: function (e) {
    var that = this;
    wx.setNavigationBarTitle({
      "title": app.appName + "--客服跟单端"
    });
    if (app.globalData.wh_id == '') {
      that.setData({
        sql_noWarehouse: true
      })
    }
    var sql_delivery_date_start = '';
    var sql_delivery_date_end = '';
    var dbtn_type = '';
    var sql_noPackage = '';
    var sql_noClose = '';
    try {
      sql_delivery_date_start = wx.getStorageSync('sql_delivery_date_start')
    } catch (e) {}
    try {
      sql_delivery_date_end = wx.getStorageSync('sql_delivery_date_start')
    } catch (e) {}
    try {
      dbtn_type = wx.getStorageSync('dbtn_type');
    } catch (e) {}
    try {
      sql_noPackage = wx.getStorageSync('sql_noPackage');
    } catch (e) {}
    try {
      sql_noClose = wx.getStorageSync('sql_noClose');
    } catch (e) {}
    that.setData({
      isAdmin: app.globalData.admin == '1' ? true : false,
      isCoAdmin: app.globalData.coAdmin == '1' ? true : false,
      default_role: app.globalData.default_role,
      server: app.server,
      sql_noPackage: sql_noPackage || false,
      sql_noClose: sql_noClose || false,
      dbtn_type: dbtn_type || 'all',
      sql_delivery_date_start: sql_delivery_date_start || util.dateObjectformat(new Date(), 'yyyy-MM-dd'),
      sql_delivery_date_end: sql_delivery_date_end || util.dateObjectformat(new Date(), 'yyyy-MM-dd'),
      price_schedule_show: app.globalData.price_schedule_show,
      CO_ID: app.globalData.CO_ID
    })
    if (app.globalData.role_default == 'operation' || app.globalData.role_default == 'admin') {
      that.setData({
        admin: true
      })
    }
    this.loadData();
  },
  filterDelivery: function (e) {
    var type = e.currentTarget.dataset.type;
    this.setData({
      dbtn_type: type
    })
    wx.setStorageSync('dbtn_type', this.data.dbtn_type);
    this.loadData();
  },
  showSearch: function () {
    this.setData({
      searchShowed: true
    });
  },
  hideSearch: function () {
    this.setData({
      searchVal: "",
      searchShowed: false
    });
    wx.setStorageSync('searchVal', this.data.searchVal);
    this.loadData();
  },
  clearSearch: function () {
    this.setData({
      searchVal: ""
    });
    wx.setStorageSync('searchVal', this.data.searchVal);
    this.loadData();
  },
  searchTyping: function (e) {
    this.setData({
      searchVal: e.detail.value
    });
    wx.setStorageSync('searchVal', this.data.searchVal);
    this.loadData();
  },
  todayDelivery: function () {
    if (this.data.delivery_date_selected) {
      this.setData({
        delivery_date: '',
        delivery_date_selected: false
      })
    } else {
      this.setData({
        delivery_date: util.dateObjectformat(new Date(), 'yyyy-MM-dd'),
        delivery_date_selected: true
      })
    }
    this.setData({
      searchVal: ""
    });
    this.loadData();
  },
  noPackage: function () {
    if (this.data.sql_noPackage) {
      this.setData({
        sql_noPackage: false
      })
    } else {
      this.setData({
        sql_noPackage: true
      })
    }
    wx.setStorageSync('sql_noPackage', this.data.sql_noPackage);
    this.loadData();
  },
  noClose: function () {
    if (this.data.sql_noClose) {
      this.setData({
        sql_noClose: false
      })
    } else {
      this.setData({
        sql_noClose: true
      })
    }
    wx.setStorageSync('sql_noClose', this.data.sql_noClose);
    this.loadData();
  },
  selectWarehouse: function () {
    wx.navigateTo({
      url: '/pages/index/warehouseList?index=0'
    })
  },
  listSort: function () {
    if (this.data.listSort == 'DESC') {
      this.setData({
        listSort: 'ASC',
        sortText: '顺序'
      })
    } else {
      this.setData({
        listSort: 'DESC',
        sortText: '倒序'
      })
    }
    wx.setStorageSync('listSort', this.data.listSort);
    this.loadData();
  },
  selectDeliveryDateStart: function (e) {
    this.setData({
      sql_delivery_date_start: e.detail.value
    });
    wx.setStorageSync('sql_delivery_date_start', e.detail.value);
    if (new Date(e.detail.value) > new Date(this.data.sql_delivery_date_end)) {
      this.setData({
        sql_delivery_date_end: util.dateObjectformat(new Date(e.detail.value), 'yyyy-MM-dd')
      })
      wx.setStorageSync('sql_delivery_date_end', e.detail.value);
    }
    this.loadData();
  },
  selectDeliveryDateEnd: function (e) {
    this.setData({
      sql_delivery_date_end: e.detail.value
    });
    wx.setStorageSync('sql_delivery_date_end', e.detail.value);
    if (new Date(e.detail.value) < new Date(this.data.sql_delivery_date_start)) {
      this.setData({
        sql_delivery_date_start: util.dateObjectformat(new Date(e.detail.value), 'yyyy-MM-dd')
      })
      wx.setStorageSync('sql_delivery_date_start', e.detail.value);
    }
    this.loadData();
  },
  setDefaultSearchVal: function () {
    try {
      wx.setStorageSync('dbtn_type', 'all');
      this.setData({
        dbtn_type: 'all'
      })
    } catch (e) {}
    try {
      wx.setStorageSync('searchVal', '')
    } catch (e) {}
    try {
      var sql_delivery_date_start = util.dateObjectformat(new Date(), 'yyyy-MM-dd');
      wx.setStorageSync('sql_delivery_date_start', sql_delivery_date_start)
      this.setData({
        sql_delivery_date_start: sql_delivery_date_start
      })
    } catch (e) {}
    try {
      var sql_delivery_date_end = util.dateObjectformat(new Date(), 'yyyy-MM-dd');
      wx.setStorageSync('sql_delivery_date_end', sql_delivery_date_end)
      this.setData({
        sql_delivery_date_end: sql_delivery_date_end
      })
    } catch (e) {}
    try {
      wx.setStorageSync('sql_noClose', '')
      this.setData({
        sql_noClose: false
      })
    } catch (e) {}
    try {
      wx.setStorageSync('sql_noClose', '')
      this.setData({
        sql_noClose: false
      })
    } catch (e) {}
    try {
      wx.setStorageSync('warehouse', '');
      this.setData({
        sql_warehouse: ''
      })
    } catch (e) {}
    try {
      wx.setStorageSync('listSort', '');
      this.setData({
        listSort: 'DESC',
        sortText: '倒序'
      })
    } catch (e) {}

    this.loadData();
  },
  loadData: function () {
    var that = this;
    wx.showLoading({
      title: '加载数据中...',
    });
    var dbtn_type = that.data.dbtn_type;
    try {
      dbtn_type = wx.getStorageSync('dbtn_type')
    } catch (e) {}
    var searchVal = that.data.searchVal;
    try {
      searchVal = wx.getStorageSync('searchVal')
    } catch (e) {}
    var sql_delivery_date_end = that.data.sql_delivery_date_end;
    try {
      sql_delivery_date_end = wx.getStorageSync('sql_delivery_date_end')
    } catch (e) {}
    var sql_delivery_date_start = that.data.sql_delivery_date_start;
    try {
      sql_delivery_date_start = wx.getStorageSync('sql_delivery_date_start')
    } catch (e) {}
    // var sql_noPackage = that.data.sql_noPackage;
    // try {
    //   sql_noPackage = wx.getStorageSync('sql_noPackage')
    // } catch (e) {}
    var sql_noClose = that.data.sql_noClose;
    try {
      sql_noClose = wx.getStorageSync('sql_noClose')
    } catch (e) {}
    var sql_warehouse = that.data.sql_warehouse;
    try {
      var warehouse = wx.getStorageSync('warehouse');
      sql_warehouse = warehouse.id;
    } catch (e) {}
    var listSort = that.data.listSort;
    try {
      var listSort = wx.getStorageSync('listSort');
    } catch (e) {}
    let condition = ''
    if (that.data.searchVal) {
      condition = "and ( path_name like '%" + that.data.searchVal + "%' or plate like '%" + that.data.searchVal + "%' or name like '%" + that.data.searchVal + "%')"
    }
    if (dbtn_type == "all") {} else if (dbtn_type == "vehicle") {
      condition += " and (vehicle != '0' and vehicle != '')  ";
    } else if (dbtn_type == "noVehicle") {
      condition += " and (vehicle = '0' or vehicle = '')  ";
    }
    if (sql_delivery_date_start && sql_delivery_date_end && sql_delivery_date_start != "" && sql_delivery_date_end != "") {
      if (sql_delivery_date_start == sql_delivery_date_end) {
        condition += " and delivery_date = '" + sql_delivery_date_start + "'  ";
      } else {
        condition += " and delivery_date >= '" + sql_delivery_date_start + "' and  delivery_date <= '" + sql_delivery_date_end + "' ";
      }
    }
    if (Number(app.globalData.admin) != 1) {
      condition += "  ";
    }
    if (sql_noClose == 'true') {
      condition += " and is_close = '0' ";
    }
    util.postData("/zhc/datalist/getDataByListId", {
      "list_id": "E323E43B-E768-407E-A067-6DF0DBD079CF",
      "page": {
        "size": that.data.pageSize,
        "current": that.data.page,
        "orders": [{
          "column": "ADD_TIME",
          "asc": that.data.listSort == 'DESC' ? false : true
        }]
      },
      "data": {
        "field": "a.path_name,a.state,a.otherfeeName,a.total_price,a.containeryard,a.wh_time,a.delivery_sort,a.driverPrice,a.deliveryThirdParty_income,a.latitude_current,a.delivery_time,a.vehicleSource,a.onePrice,a.tp_time,a.deliveryPrice,a.unload_box,a.month_knot_income,a.mileage,a.configExplain,a.deliveryThirdParty_pay,a.ADD_USER,a.remoteGetVehicle,a.volume,a.parkingfee,a.delivery_mile,a.packages_expect,a.ctime,a.parkingfee_docs_compress,a.back_box,a.wh_remark,a.loading_rule,a.parkingfee_docs,a.ADD_USER_NAME,a.depart_time,a.wh_status,a.is_auction,a.cy_get,a.driverPrice2,a.onePrice_income,a.return_package,a.humidity_current,a.temperature_current,a.is_account_checking,a.total_package,a.delivery_point,a.cost2,a.deliveryOntime,a.deliveryEvaluation,a.vehicle_level,a.longitude_current,a.work_after_check,a.is_account_confirm,a.warehouse,a.driver,a.cost,a.work_before_check,a.custom_distance,a.loading_time,a.signin,a.auction_price_min,a.auction_price_max,a.total_weight,a.delivery_score,a.delivery_date,a.weight,a.ID,a.driver_status,a.delivery_picture,a.onePrice2,a.goodsValue,a.shipper_path,a.back_distance,a.income_pricemode,a.wh_user,a.deliveryMode,a.total_mileage,a.vehicleFunction,a.month_knot_pay,a.total_cbm,a.is_undertaking,a.tollfee_docs,a.specialPrice,a.customerName,a.cy_image,a.isReturn,a.receiving_order,a.vehicleLength,a.wh_attachment,a.tollfee,a.urgentGetVehicle,a.total_duration,a.franchiseDriverPrice,a.auction_vehicle_tags,a.is_close,a.driver_level,a.NO,a.is_cancel,a.returnBoxs,a.otherfee,a.packages,a.goodsname,a.remark,a.ADD_TIME,a.vehicle,a.back_duration,a.auction_param,a.create_mode,a.BE_DEL,a.CO_ID"
      },
      "repeat_field": [],
      "condition": " a.CO_ID='" + app.globalData.CO_ID + "'  " + condition,
      "virtual_field": [{
          "relate": "LEFT JOIN",
          "res": "47bb1f0ec0874fb5961186f86b97792e",
          "alias": "b",
          "on": "a.vehicle=b.ID",
          "type": "",
          "condition": "",
          "from_field": "plate",
          "field_name": "plate",
          "field_alias": "车牌"
        },
        {
          "relate": "LEFT JOIN",
          "res": "88e65a5ccd734a35a0cac74c9d58ff2e",
          "alias": "c",
          "on": "a.driver=c.ID",
          "type": "",
          "condition": "",
          "from_field": "name",
          "field_name": "driver_name",
          "field_alias": "司机"
        },
        {
          "relate": "LEFT JOIN",
          "res": "755fb921d96f4db59773592b345fd7e1",
          "alias": "d",
          "on": "a.ID=d.delivery",
          "type": "COUNT",
          "condition": "",
          "from_field": "ID",
          "field_name": "shop_number",
          "field_alias": "配送点数量"
        }
      ]
    }, function (res, error) {
      console.log(res);
      console.log(error)
      if (res.data.success && res.data?.result?.records.length > 0) {
        var count = res.data.result.total;
        that.setData({
          hasData: true
        });
        var data = res.data.result.records,
          _data = [];
        for (var i = 0; i < data.length; i++) {
          if (data[i].driver_status == "0") {
            if (data[i].is_undertaking == 1 && data[i].receiving_order == 0) {
              data[i].status = '已签承诺书';
              data[i].color = '#999';
            } else if (data[i].is_undertaking == 1 && data[i].receiving_order == 1) {
              data[i].status = '已接单';
              data[i].color = 'orange';
            } else {
              data[i].status = '未开始';
              data[i].color = '#999';
            }
            //stats.nostart += 1;
          } else if (data[i].driver_status == "start") {
            data[i].status = '配送中';
            data[i].color = 'blue';
            //stats.delivery += 1;
          } else if (data[i].driver_status == "delivery_end") {
            data[i].status = '配送完成';
            data[i].color = 'blue';
            // stats.delivery += 1;
          } else if (data[i].driver_status == "end") {
            data[i].status = '配送结束';
            data[i].color = 'green';
            //stats.end += 1;
            //if(n.is_close == 0){
            //    stats.nocloseOfEnd += 1;
            // }
          } else {
            data[i].status = '配送中';
            data[i].color = 'blue';
            //stats.delivery += 1;
          }
          var tollfee_docs = [];
          var tollfee_docs_compress = [];
          var parkingfee_docs = [];
          var parkingfee_docs_compress = [];
          var delivery_picture = [];
          if (data[i].delivery_picture) {
            delivery_picture = util.imagesArray(String(data[i].delivery_picture).split(','), app.server);
          }
          if (data[i].tollfee_docs) {
            tollfee_docs = util.imagesArray(String(data[i].tollfee_docs).split(','), app.server);
          }
          if (data[i].tollfee_docs_compress) {
            tollfee_docs_compress = util.imagesArray(String(data[i].tollfee_docs_compress).split(','), app.server);
          }
          if (data[i].parkingfee_docs) {
            parkingfee_docs = util.imagesArray(String(data[i].parkingfee_docs).split(','), app.server);
          }
          if (data[i].parkingfee_docs_compress) {
            parkingfee_docs_compress = util.imagesArray(String(data[i].parkingfee_docs_compress).split(','), app.server);
          }
          var CO_ID = data[i].CO_ID,
            vehicle_coid = data[i].vehicle_coid,
            capacity_company = data[i].capacity_company;
          var is_myVehicle = data[i].CO_ID == app.globalData.CO_ID? true : false;

          var taxrate = data[i].taxrate == 0 ? app.globalData.taxrate : data[i].taxrate
          if (isNaN(taxrate) == false && taxrate > 0) {
            taxrate = 1 + taxrate / 100;
          } else {
            taxrate = 1;
          }
          if (app.globalData.income_taxes == 0) {
            taxrate = 1;
          }

          // that.setData({
          //   isCloseRole:util.getCloseDeliveryROle(app.globalData.roleData,CO_ID)
          // })

          var income = Number(data[i].total_price) / taxrate,
            pay = data[i].driverPrice;
          //托运价格。仓库是我的，单不是我派的
          if (data[i].wh_coid == app.globalData.CO_ID && CO_ID != app.globalData.CO_ID) {
            console.log(data[i].path_name + ':aaaaaaaaaaaaa');
            income = 0;
            pay = data[i].deliveryPrice;
            data[i].carrier_vehicle = data[i].vehicle;
          }
          //自有业务计价。仓库是我的，单是我派的
          if (data[i].wh_coid == CO_ID && CO_ID == app.globalData.CO_ID) {
            console.log(data[i].path_name + ':bbbbbbbbbb');
            if (data[i].vehicle_coid == CO_ID) {
              pay = data[i].driverPrice;
              data[i].carrier_coid = data[i].vehicle_coid;
            } else if (data[i].vehicle_coid == 0) {
              pay = data[i].driverPrice;
              data[i].carrier_vehicle = data[i].vehicle;
            } else if (data[i].vehicle_coid && data[i].vehicle_coid != 0) {
              pay = data[i].cost;
              data[i].carrier_coid = data[i].vehicle_coid;
            } else {
              pay = data[i].driverPrice;
            }
          }
          //承运业务计价，托运方承运。仓库不是我的，单是我派的
          if (data[i].wh_coid != CO_ID && CO_ID == app.globalData.CO_ID) {
            console.log(data[i].path_name + ':cccccccccc');
            console.log(data[i].path_name + ':' + data[i].total_price);
            income = Number(data[i].total_price) / taxrate;
            if (data[i].vehicle_coid == CO_ID) {
              pay = data[i].driverPrice;
              data[i].carrier_vehicle = data[i].vehicle;
            } else if (data[i].vehicle_coid == 0) {
              pay = data[i].driverPrice;
              data[i].carrier_vehicle = data[i].vehicle;
            } else {
              pay = data[i].cost;
              data[i].carrier_coid = data[i].vehicle_coid;
            }
          }
          //承运业务计价，派遣车辆承运。单不是我派的，车是我的
          if (CO_ID != app.globalData.CO_ID && data[i].vehicle_coid == app.globalData.CO_ID) {
            income = Number(data[i].cost2 > 0 ? data[i].cost2 : data[i].cost) / taxrate;
            pay = data[i].driverPrice;
            data[i].carrier_vehicle = data[i].vehicle;
            console.log(data[i].path_name + ':ddddddddddd');
          }
          //二级承运业务计价。单不是我的，单派遣给我派车，建单方看
          if (data[i].carrier && data[i].carrier != CO_ID) {
            console.log(data[i].path_name + ':fffff');
            pay = data[i].cost;
            data[i].carrier_vehicle = data[i].vehicle;
          }
          //二级承运业务计价。单不是我的，单派遣给我派车，承运商看
          if (data[i].carrier == app.globalData.CO_ID && CO_ID != app.globalData.CO_ID) {
            console.log(data[i].path_name + ':eeeeeeee');
            income = Number(data[i].cost2 > 0 ? data[i].cost2 : data[i].cost) / taxrate;
            pay = data[i].driverPrice;
            data[i].carrier_vehicle = data[i].vehicle;
          }

          if (data[i].wh_time == '0000-00-00 00:00:00') {
            data[i].wh_time = data[i].delivery_date + ' 00:00:00'
          }
          if (app.globalData.deleteRole == true) {
            data[i].deleteRole = true;
          } else {
            if (data[i].driver_status == 0 && app.globalData.role_default == "schedule" && data[i].receiving_order == 0) {
              data[i].deleteRole = true;
            } else {
              data[i].deleteRole = false;
            }
          }
          if (income == 'undefined' || !income == true) {
            income = 0;
          }
          if (pay == 'undefined' || !pay == true) {
            pay = 0;
          }
          _data.push({
            ID: data[i].ID,
            NO: data[i].NO,
            BE_DEL: data[i].BE_DEL,
            CO_ID: data[i].CO_ID,
            vehicleId: data[i].vehicle,
            driverId: data[i].driver,
            iot_box: data[i].iot_box,
            path_name: data[i].path_name,
            ADD_TIME: moment(data[i].ADD_TIME).format('YYYY年MM月DD日 HH时mm分'),
            wh_name: data[i].wh_name,
            wh_address: data[i].wh_address,
            shop_number: data[i].shop_number,
            total_mileage: data[i].total_mileage || 0,
            total_duration: data[i].total_duration || 0,
            vehicle_coid: data[i].vehicle_coid,
            capacity_company: data[i].capacity_company,
            wh_coid: data[i].wh_coid,
            income: util.toFixedPlus(income, 2),
            pay: util.toFixedPlus(pay, 2),
            profit: (Number(data[i].total_price || 0) - Number(data[i].cost || 0) > 0) ? true : false,
            onePrice: Number(data[i].onePrice),
            onePrice_income: Number(data[i].onePrice_income),
            order_state: data[i].driver_status,
            plate: data[i].plate,
            driver_name: data[i].driver_name,
            delivery_mile: data[i].delivery_mile ? (Number(data[i].delivery_mile) / 1000).toFixed(1) : 0,
            delivery_time: Number(data[i].delivery_time).toFixed(2) || 0,
            delivery_date: data[i].delivery_date,
            loading_time: moment(data[i].loading_time).format('YYYY-MM-DD HH:mm'),
            delivery_sort: data[i].shop_receive,
            isPublish: (data[i].isPublish == '1' ? false : true),
            isChangeVehicle: (data[i].driver_status != "end" ? true : false),
            packages_expect: data[i].packages_expect || 0,
            packages: data[i].packages || 0,
            volume: data[i].volume || 0,
            unload_box: data[i].unload_box || 0,
            back_box: data[i].back_box || 0,
            weight: data[i].weight || 0,
            goodsValue: data[i].goodsValue ? Number(data[i].goodsValue).toFixed(1) : 0,
            warehouse: data[i].warehouse,
            delivery_picture: delivery_picture,
            tollfee: data[i].tollfee,
            tollfee_docs: tollfee_docs,
            tollfee_docs_compress: tollfee_docs_compress,
            parkingfee: data[i].parkingfee,
            parkingfee_docs: parkingfee_docs,
            parkingfee_docs_compress: parkingfee_docs_compress,
            otherfeeName: data[i].otherfeeName,
            otherfee: data[i].otherfee,
            back_distance: data[i].back_distance == 'undefined' ? 0 : data[i].back_distance,
            vehicle_level: data[i].vehicle_level,
            driver_level: data[i].driver_level,
            month_knot_income: data[i].month_knot_income != null ? data[i].month_knot_income : data[i].wh_month_knot_income,
            month_knot_pay: data[i].month_knot_pay != null ? data[i].month_knot_pay : data[i].wh_month_knot_pay,
            carrier: data[i].carrier,
            is_close: data[i].is_close,
            is_cancel: data[i].is_cancel,
            isAdmin: that.data.isAdmin,
            is_myVehicle: is_myVehicle,
            custom_distance: data[i].custom_distance,
            is_custom_distance: data[i].is_custom_distance,
            IS_DEL: data[i].IS_DEL,
            deleteRole: data[i].deleteRole,
            status: data[i].status,
            color: data[i].color,
            driver_status: data[i].driver_status,
            loadingrule: data[i].loading_rule || data[i].loadingrule,
            is_auction: data[i].is_auction,
            carrier_vehicle: data[i].carrier_vehicle || '',
            carrier_coid: data[i].carrier_coid || '',
            unit: data[i].unit || '件',
            goodsname: data[i].goodsname || '',
            customerName: data[i].customerName || '',
            taxrate: taxrate,
            monthly_income: Number(data[i].monthly_income),
            return_package: Number(data[i].return_package || 0),
            deliveryThirdParty_income: Number(data[i].deliveryThirdParty_income),
            deliveryThirdParty_pay: Number(data[i].deliveryThirdParty_pay),
            tags: data[i].tags || '',
            vehicleLength: data[i].vehicleLength || '',
            driverPrice: data[i].driverPrice,
            total_price:data[i].total_price
          });
          // that.setData({
          //   order_state: data[i].state
          // });
        };
        var pageNumber = Math.ceil(count / that.data.pageSize);
        that.setData({
          order_list: _data,
          count: count,
          page: that.data.page == 0 ? 1 : that.data.page,
          pageNumber: pageNumber
        });
        that.setPageStatus();
        // if (that.data.order_state == "0" || that.data.order_state == "2" || that.data.order_state == "4") {
        //   that.setData({
        //     order_flow_btn: false
        //   });
        // }
      } else {
        that.setData({
          hasData: false,
          count: 0,
          pageNumber: 0,
          page: 0,
          firstPage: true,
          prevPage: true,
          nextPage: true,
          lastPage: true
        })
      };
      //停住下拉刷新
      //that.stopPullDownRefresh();
      wx.hideLoading();
      setTimeout(function () {
        wx.hideLoading();
      }, 100)
    });
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page,
      pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      if (this.data.page > 1) {
        this.setData({
          page: this.data.page - 1
        })
        this.loadData();
      }
    }
    if (type == 'next') {
      if (this.data.page < this.data.pageNumber) {
        this.setData({
          page: this.data.page + 1
        })
        this.loadData();
      }
    }
  },
  changeDeliveryDate: function (e) {
    var that = this;
    console.log(e)
    var id = e.currentTarget.id;
    var date = e.detail.value;
    wx.showModal({
      title: '运单日期修改',
      content: '是否确认修改运单日期为：' + date + '？',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '请稍候...',
          });
          util.postData("/sys/form/commonUpdate",{
            "formId":"6E6999E1-1A6B-4F98-B1A4-A0A6BD77FAFC",
            "data":[{
                "dataId":id,
                "target":{"delivery_date":date}
            }],
            "condition":""
            }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: "修改成功",
                icon: 'success',
                success: function () {
                }
              });
            }else{
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
        } else if (res.cancel) {}
      }
    })
  },
  changeLoadingtime: function (e) {
    var that = this;
    var edit = e.currentTarget.dataset.edit;
    if (edit == 'false') {
      return false;
    }
    var loadingtime = e.currentTarget.dataset.loadingtime;
    that.setData({
      currentId: e.currentTarget.dataset.id,
      datetime_picker: new Date(loadingtime).getTime(),
      loadingtime: loadingtime,
      datetime_picker_show: true,
      loading_time_is_change: false
    })
  },
  datetimePicker: function (e) {
    console.log(e)
    var picker_loading_time = moment(e.detail).format('YYYY-MM-DD HH:mm');
    this.setData({
      picker_loading_time: picker_loading_time
    })
  },
  datetimePickerCancel: function () {
    this.setData({
      datetime_picker_show: false
    })
  },
  datetimePickerChange: function () {
    this.setData({
      loading_time_is_change: true
    })
  },
  datetimePickerConfirmBeforeCheck: function () {
    var that = this;
    if (that.data.loading_time_is_change) {
      that.datetimePickerConfirm()
    } else {
      wx.showLoading({
        title: '请稍候...',
      });
      var dpi = setInterval(function () {
        if (that.data.loading_time_is_change) {
          wx.hideLoading();
          that.datetimePickerConfirm()
          clearInterval(dpi)
        }
      }, 100);
      if (that.data.picker_loading_time == that.data.loadingtime) {
        wx.hideLoading();
        that.setData({
          datetime_picker_show: false,
          loading_time_is_change: false
        })
      }
    }
  },
  datetimePickerConfirm: function () {
    var that = this;
    that.setData({
      datetime_picker_show: false,
      loading_time_is_change: false
    })
    wx.showModal({
      title: '提货时间修改',
      content: '是否确认修改提货时间为：' + that.data.picker_loading_time + '？',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '请稍候...',
          });
          util.putData("/atapi/delivery/process/changeLoadingtime", {
            id: that.data.currentId,
            loading_time: that.data.picker_loading_time,
            old_loading_time: that.data.loadingtime,
            unionid: app.globalData.unionid,
            'CO_ID': app.globalData.CO_ID,
            'user_id': app.globalData.user_id,
            truename: app.globalData.truename
          }, function (res, error) {
            console.log(res);
            console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
            if (res.data.success) {
              var order_list = that.data.order_list;
              for (var i = 0; i < order_list.length; i++) {
                if (order_list[i].ID == that.data.currentId) {
                  order_list[i].loading_time = moment(that.data.picker_loading_time).format('YYYY-MM-DD HH:mm');
                }
              }
              that.setData({
                order_list: order_list
              })
              wx.showToast({
                title: "修改成功",
                icon: 'success',
                success: function () {
                  setTimeout(function () {
                    that.loadData();
                  }, 2000)
                }
              });
            } else {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
        } else if (res.cancel) {}
      }
    })

  },
  setDeliveryCancel: function (e) {
    var id = e.currentTarget.id;
    wx.showModal({
      title: '作废运单',
      content: '是否确认作废运单',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '请稍候...',
          });
          util.putData("setDeliveryCancel", {
            id: id,
            openid: app.globalData.openid,
            'CO_ID': app.globalData.CO_ID,
            'user_id': app.globalData.user_id
          }, function (res, error) {
            console.log(res);
            console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: "作废成功",
                icon: 'success',
                success: function () {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/schedule/schedule'
                    })
                  }, 3000);
                }
              });
            }
          });
        } else if (res.cancel) {}
      }
    })
  },
  deleteDeliveryForm: function (e) {
    var id = e.currentTarget.id;
    wx.showModal({
      title: '删除运单',
      content: '是否确认删除运单',
      success: function (res) {
        if (res.confirm) {
          wx.showLoading({
            title: '请稍候...',
          });
          util.putData("deleteDeliveryForm", {
            id: id,
            openid: app.globalData.openid,
            'CO_ID': app.globalData.CO_ID,
            'user_id': app.globalData.user_id
          }, function (res, error) {
            console.log(res);
            console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: "删除成功",
                icon: 'success',
                success: function () {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/schedule/schedule'
                    })
                  }, 3000);
                }
              });
            }
          });
        } else if (res.cancel) {}
      }
    })
  },
  cannelCloseDelivery: function (e) {
    var id = e.currentTarget.id;
    var that = this;
    wx.showModal({
      title: '确认取消关单',
      content: '确认取消关单？涉及的调度员/跟单员和司机有可能可以修改部分内容！',
      success: function (res) {
        if (res.confirm) {
          
          util.postData("/sys/form/commonUpdate",{
            "formId":"6E6999E1-1A6B-4F98-B1A4-A0A6BD77FAFC",
            "data":[{
                "dataId":id,
                "target":{"is_close":0}
            }],
            "condition":""
            }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              return false;
            }
            if (res.data.success) {
              that.setData({
                modalName: null
              })
              wx.showToast({
                title: "取消关单成功",
                icon: 'success',
                success: function () {
                  setTimeout(function () {
                    that.loadData();
                  }, 3000);
                }
              });
            }else{
              wx.showToast({
                title: "取消关单失败",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
        }
      }
    });
  },
  chooseDeliveryDocumentsImage: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var point_data = that.data.currentDeliveryPoint,
      currentPoint = {};
    for (var i = 0; i < point_data.length; i++) {
      if (point_data[i].ID == id) {
        currentPoint = point_data[i]
      }
    }

    wx.chooseMedia({
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        var size = Number(res.tempFiles[0].size || 1024000) / 1024;
        console.log(size)
        wx.showLoading({
          title: '上传中...'
        });
        var formData = {
          'id': id,
          'picture': JSON.stringify(currentPoint.picture),
          'picture_compress': JSON.stringify(currentPoint.picture_compress)
        };
        if (size > 500) {
          wx.compressImage({
            src: res.tempFiles[0].tempFilePath, // 图片路径
            quality: 80,
            success: function (res) {
              console.log('压缩')
              var url = res.tempFilePath;
              that.uploadFile(url, formData, currentPoint, id)
            }
          })
        } else {
          console.log('不压缩')
          var url = res.tempFiles[0].tempFilePath;
          that.uploadFile(url, formData, currentPoint, id)
        }
      }
    })
  },
  uploadFile: function (url, formData, currentPoint, id) {
    var that = this;
    wx.uploadFile({
      url: app.server + '/commons/file/uploads',
      header: {
        'Authorization': app.globalData.token
      },
      filePath: url,
      name: 'file',
      formData: formData,
      success: function (res) {
        var data = JSON.parse(res.data);
        console.log(data)
        if (data.success) {
          var point_data = that.data.currentDeliveryPoint;
          for (var i = 0; i < point_data.length; i++) {
            if (point_data[i].ID == id) {
              currentPoint.picture.push(data.result[0]);
              point_data[i] = currentPoint
            }
          }
          that.setData({
            currentDeliveryPoint: point_data
          })
          //更新到运单表
          util.postData("/sys/form/commonUpdate",{
            "formId":"1188A557-71F4-47EB-96C8-8AFE6E866C11",
            "data":[{
                "dataId":id,
                "target":{"picture":currentPoint.picture.join(',')}
            }],
            "condition":""
            }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: "修改成功",
                icon: 'success',
                success: function () {
                }
              });
            }else{
              wx.showToast({
                title: res.data.data,
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
        } else {
          wx.showToast({
            title: "上传失败",
            image: '/images/wrong.png',
            duration: 2000
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  DelDocsImg: function (e) {
    var that = this;
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除图片吗？',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...'
          });
          var id = e.currentTarget.dataset.id;
          var picture_compress = e.currentTarget.dataset.picture_compress
          var picture = e.currentTarget.dataset.picture;
          console.log(picture_compress)
          var point_data = that.data.currentDeliveryPoint;
          var currentPoint = {};
          for (var i = 0; i < point_data.length; i++) {
            if (point_data[i].ID == id) {
              currentPoint = point_data[i];
              var _picture_compress = point_data[i].picture_compress;
              var _picture_compress_ = [];
              for (var j in _picture_compress) {
                if (_picture_compress[j] != picture_compress) {
                  _picture_compress_.push(_picture_compress[j])
                }
              }
              point_data[i].picture_compress = _picture_compress_;

              var _picture = point_data[i].picture;
              var _picture_ = [];
              for (var j in _picture) {
                if (_picture[j] != picture) {
                  _picture_.push(_picture[j])
                }
              }
              point_data[i].picture = _picture_;
            }
          }
          that.setData({
            currentDeliveryPoint: point_data
          })
          util.putData("/atapi/delivery/process/deleteDocsFile", {
            id: id,
            url: picture_compress,
            url2: picture,
            picture_compress: currentPoint.picture_compress.join(','),
            picture: currentPoint.picture.join(',')
          }, function (res, error) {
            console.log(res);
            console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: '删除失败',
                image: '/images/wrong.svg',
                duration: 2000
              });
              return false;
            }
            if (res.data.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000,
                success: function () {

                }
              });
            } else {
              wx.showToast({
                title: '删除失败',
                image: '/images/wrong.svg',
                duration: 2000
              });
            }
          });
        }
      }
    })
    return false;
  },
  previewDocsImage: function (e) {
    var that = this;
    var url = e.currentTarget.dataset.url;
    var id = e.currentTarget.dataset.id;
    var point_data = that.data.currentDeliveryPoint;
    var urls = [];
    for (var i = 0; i < point_data.length; i++) {
      if (point_data[i].ID == id) {
        urls = point_data[i].picture;
      }
    }
    for (var i in urls) {
      if (String(urls[i]).indexOf('http') == -1) {
        urls[i] = that.data.server + urls[i];
      }
    }
    wx.previewImage({
      current: url,
      urls: urls
    })
  },
  closeDelivery: function (e) {
    var id = e.currentTarget.id;
    var that = this;
    var order_list = that.data.order_list;
    var currentDelivery = {};
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == id) {
        currentDelivery = order_list[i];
        break;
      }
    }
    var closeDeliveryCheckList = [
      //{ name: '运费核查', class:'', checked: true },
      //{ name: '收入价格', class: 'wrong red', checked: false },
      {
        type: 'state',
        name: '运输状态核查',
        class: 'wait',
        checked: 'nocheck'
      },
      {
        type: 'package',
        name: '运输货品数量',
        class: 'wait',
        checked: 'nocheck'
      },
      {
        type: 'price',
        name: '运费计算结果核查',
        class: 'wait',
        checked: 'nocheck'
      } //,
      //{ type: 'documents', name: '单据核查', class: 'wait', checked: 'nocheck' }
    ];
    that.setData({
      modalName: 'closeDeliveryModal',
      currentDelivery: currentDelivery,
      closeDeliveryCheckList: closeDeliveryCheckList
    })
    console.log(currentDelivery)

    for (var i = 0; i < closeDeliveryCheckList.length; i++) {
      //运输状态核查
      if (closeDeliveryCheckList[i].type == 'state') {
        if (currentDelivery.driver_status == 'end') {
          closeDeliveryCheckList[i].name = '运单已结束';
          closeDeliveryCheckList[i].class = '';
          closeDeliveryCheckList[i].checked = true;
          that.setData({
            closeDeliveryBtn: false
          })
        } else {
          that.setData({
            closeDeliveryBtn: true
          })
          closeDeliveryCheckList[i].name = '运单未结束，不能关单';
          closeDeliveryCheckList[i].class = 'wrong red';
          closeDeliveryCheckList[i].checked = true;
        }
        that.setData({
          closeDeliveryCheckList: closeDeliveryCheckList
        })
      }
      //运输货品数量
      if (closeDeliveryCheckList[i].type == 'package') {
        if (currentDelivery.packages_expect > 0) {
          closeDeliveryCheckList[i].name = '有运输货品数量，请核查数量是否符合';
          closeDeliveryCheckList[i].class = '';
          closeDeliveryCheckList[i].checked = true;
        } else {
          closeDeliveryCheckList[i].name = '运输货品数量为0';
          closeDeliveryCheckList[i].class = 'wrong red';
          closeDeliveryCheckList[i].checked = true;
        }
        that.setData({
          closeDeliveryCheckList: closeDeliveryCheckList
        })
      }
      //运费计算结果核查
      if (closeDeliveryCheckList[i].type == 'price') {
        var income = false,
          pay = false
        if (currentDelivery.income > 0) {
          income = true
        }
        if (currentDelivery.pay > 0) {
          pay = true
        }
        if (income == true && pay == true) {
          closeDeliveryCheckList[i].name = '价格显示正常，请核查是否符合实际运费';
          closeDeliveryCheckList[i].class = '';
          closeDeliveryCheckList[i].checked = true;
        } else {
          closeDeliveryCheckList[i].name = '价格异常，请重新计算价格或者核查价格配置';
          closeDeliveryCheckList[i].class = 'wrong red';
          closeDeliveryCheckList[i].checked = true;
        }
        that.setData({
          closeDeliveryCheckList: closeDeliveryCheckList
        })
      }
      //单据核查
      // if (closeDeliveryCheckList[i].type == 'documents') {
      //   if (currentDelivery.delivery_picture.length > 0) {
      //     closeDeliveryCheckList[i].name = '司机有上传单据，请核查是否正确和清晰';
      //     closeDeliveryCheckList[i].class = '';
      //     closeDeliveryCheckList[i].checked = true;
      //   } else {
      //     closeDeliveryCheckList[i].name = '司机未有上传单据';
      //     closeDeliveryCheckList[i].class = 'wrong red';
      //     closeDeliveryCheckList[i].checked = true;
      //   }
      //   that.setData({
      //     closeDeliveryCheckList: closeDeliveryCheckList
      //   })
      // }
    }

  },
  closeDeliveryComplete: function () {
    var that = this;
    var currentDelivery = that.data.currentDelivery;
    wx.showModal({
      title: '确认关单',
      content: '确认已经核查过运单所有数据？一旦关单将无法更改！',
      success: function (res) {
        if (res.confirm) {
          util.postData("/sys/form/commonUpdate",{
            "formId":"6E6999E1-1A6B-4F98-B1A4-A0A6BD77FAFC",
            "data":[{
                "dataId":currentDelivery.ID,
                "target":{"is_close":1}
            }],
            "condition":""
            }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              return false;
            }
            if (res.data.success) {
              that.setData({
                modalName: null
              })
              wx.showToast({
                title: "关单成功",
                icon: 'success',
                success: function () {
                  setTimeout(function () {
                    that.loadData();
                  }, 3000);
                }
              });
            }else{
              wx.showToast({
                title: "关单失败",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
        }
      }
    });
  },
  setDeliveryEnd: function () {
    var that = this;
    var currentDelivery = that.data.currentDelivery;
    wx.showModal({
      title: '确认强制关单',
      content: '改运单未结束，确认强制关单吗？将会自动结束运单和关单。',
      success: function (res) {
        if (res.confirm) {
          util.postData("/sys/form/commonUpdate",{
            "formId":"6E6999E1-1A6B-4F98-B1A4-A0A6BD77FAFC",
            "data":[{
                "dataId":currentDelivery.ID,
                "target":{"is_close":1,"driver_status":"end"}
            }],
            "condition":""
            }, function (res, error) {
            console.log(res); console.log(error)
            wx.hideLoading();
            if (error) {
              return false;
            }
            if (res.data.success) {
              that.setData({
                modalName: null
              })
              wx.showToast({
                title: "关单成功",
                icon: 'success',
                success: function () {
                  setTimeout(function () {
                    that.loadData();
                  }, 3000);
                }
              });
            }else{
              wx.showToast({
                title: "关单失败",
                image: '/images/wrong.png',
                duration: 3000
              });
            }
          });
        }
      }
    });
  },
  changeDeliveryPoint: function (e) {
    wx.redirectTo({
      url: '/pages/schedule/changePoint?id=' + e.currentTarget.id + '&warehouse=' + e.currentTarget.dataset.warehouse
    })
  },
  assignVehicle: function (e) {
    var order_list = this.data.order_list,
      id = e.currentTarget.id,
      currentDelivery = '';
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == id) {
        currentDelivery = order_list[i];
        break;
      }
    }
    console.log(currentDelivery)
    wx.redirectTo({
      url: '/pages/schedule/delivery_vehicle?type=assign&delivery=' + id + '&warehouse=' + currentDelivery.warehouse + '&loadingDate=' + currentDelivery.loading_time + '&vehicleLength=' + currentDelivery.vehicleLength + '&tags=' + currentDelivery.tags
    })
  },
  changeVehicle: function (e) {
    var order_list = this.data.order_list,
      id = e.currentTarget.id,
      currentDelivery = '';
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == id) {
        currentDelivery = order_list[i];
        break;
      }
    }
    console.log(currentDelivery)
    wx.redirectTo({
      url: '/pages/schedule/delivery_vehicle?type=change&delivery=' + id + '&warehouse=' + currentDelivery.warehouse + '&loadingDate=' + currentDelivery.loading_time + '&vehicleLength=' + currentDelivery.vehicleLength + '&tags=' + currentDelivery.tags
    })
  },
  moreConfig: function (e) {
    var that = this;
    var id = e.currentTarget.id;
    var vehicleId = e.currentTarget.dataset.vehicle;
    that.setData({
      modalName: e.currentTarget.dataset.target,
      currentId: id,
      currentVehicleId: vehicleId,
      vcoid: e.currentTarget.dataset.vcoid,
      dcoid: e.currentTarget.dataset.dcoid
    });
  },
  //重新计算费用
  recalculatePrice: function () {
    var that = this;
    that.setData({
      modalName: null
    });
    var order_list = that.data.order_list;
    wx.showModal({
      title: '温馨提示',
      content: '确定要重新计算费用吗？',
      success: function (res) {
        if (res.confirm) {
          that.recalculatePriceSubmit();
        }
      }
    });

  },
  recalculatePriceSubmit: function () {
    var that = this;
    util.postData("calculatePriceWithDeliveryId", {
      id: that.data.currentId,
      openid: app.globalData.openid,
      'CO_ID': app.globalData.CO_ID,
      'user_id': app.globalData.user_id
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: "重新计算成功",
          icon: 'success',
          success: function () {
            setTimeout(function () {
              that.loadData();
            }, 3000);
          }
        });
      }
    });
  },
  //重新计算里程和费用
  recalculatePriceAndDistance: function () {
    var that = this;
    that.setData({
      modalName: null
    });
    var order_list = that.data.order_list;
    var hasOnePrice = false;
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == that.data.currentId && (order_list[i].onePrice > 0 || order_list[i].onePrice_income > 0)) {
        hasOnePrice = true;
      }
    }
    if (hasOnePrice) {
      wx.showModal({
        title: '温馨提示',
        content: '该运单已经设置了一口价，如果要重新计算费用，请先设置一口价为0？',
        success: function (res) {
          if (res.confirm) {

          }
        }
      });
    } else {
      that.recalculatePriceAndDistanceSubmit();
    }
  },
  recalculatePriceAndDistanceSubmit: function () {
    var that = this;
    util.postData("calculateDistanceWithDeliveryId", {
      id: that.data.currentId,
      openid: app.globalData.openid,
      'CO_ID': app.globalData.CO_ID,
      'user_id': app.globalData.user_id
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: "重新计算成功",
          icon: 'success',
          success: function () {
            setTimeout(function () {
              that.loadData();
            }, 3000);
          }
        });
      }
    });
  },
  //设为一口价，支出
  setOnePricePay: function () {
    var that = this;
    var order_list = that.data.order_list;
    var onePrice = 0;
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == that.data.currentId) {
        onePrice = order_list[i].pay;
        break;
      }
    }
    that.setData({
      modalName: null,
      setOnePriceId: that.data.currentId,
      onePrice: onePrice,
      oldOnePrice: onePrice,
      onePriceTypeOfPay: true,
      dialog: true
    })
  },
  //设为一口价，收入
  setOnePriceIncome: function () {
    var that = this;
    var order_list = that.data.order_list;
    var onePrice = 0;
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == that.data.currentId) {
        onePrice = order_list[i].income;
        break;
      }
    }
    that.setData({
      modalName: null,
      setOnePriceId: that.data.currentId,
      onePrice: onePrice,
      oldOnePrice: onePrice,
      onePriceTypeOfPay: false,
      dialog: true
    })
  },
  //车辆放空
  vehicleEmpty: function () {
    var that = this;
    that.setData({
      modalName: null,
      vehicle_empty_dialog: true
    })
  },
  //接驳费
  deliveryThirdParty: function () {
    var that = this;
    that.setData({
      modalName: 'deliveryThirdParty'
    })
    var id = that.data.currentId;
    var order_list = that.data.order_list;
    var currentDelivery = {};
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == id) {
        currentDelivery = order_list[i];
        break;
      }
    }
    that.setData({
      currentDelivery: currentDelivery
    })
    this.getCurrentOrderGoods(currentDelivery)
  },
  //计价详情
  showPriceDetail: function (e) {
    var that = this;
    that.setData({
      modalName: null
    });
    var id = that.data.currentId;
    wx.showLoading({
      title: '获取计价数据中...',
    });
    util.getData("/atapi/price/price/priceDetail", {
      id: id
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        that.setData({
          priceDetail: res.data.data
        })
      }
      that.setData({
        modalName: 'priceDetail'
      })
    });
  },
  paymentRequest: function () {
    var that = this;
    var order_list = that.data.order_list;
    var warehouse = '';
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == that.data.currentId) {
        warehouse = order_list[i].warehouse;
        break;
      }
    }
    wx.redirectTo({
      url: '/pages/finance/payment_request?order=' + that.data.currentId + "&warehouse=" + warehouse,
    })
  },
  //运费收入方式
  priceIncomeMode: function () {
    var that = this;
    that.setData({
      modalName: null
    })
    var order_list = that.data.order_list;
    var month_knot_income = 1;
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == that.data.currentId) {
        month_knot_income = order_list[i].month_knot_income;
        break;
      }
    }
    wx.showModal({
      title: '运费支付方式',
      content: '更改运费收入方式，如果是现结，请确定已收款！',
      confirmText: '月结',
      cancelText: '现结',
      success(res) {
        if (res.confirm) {
          if (Number(month_knot_income) != 1) {
            wx.showLoading({
              title: '更改中...',
            });
            util.putData("/atapi/delivery/process/priceIncomeMode", {
              id: that.data.currentId,
              type: 'month_knot_income',
              value: 1,
              'CO_ID': app.globalData.CO_ID,
              'user_id': app.globalData.user_id
            }, function (res, error) {
              wx.hideLoading();
              if (error) {
                wx.showToast({
                  title: res.data.data,
                  image: '/images/wrong.png',
                  duration: 3000
                });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: '已设：月结模式',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function () {
                      that.loadData();
                    }, 3000);
                  }
                });
              }
            });
          } else {
            wx.showToast({
              title: '已是月结模式',
              icon: 'success',
              duration: 2000
            });
          }
        } else if (res.cancel) {
          if (Number(month_knot_income) != 0) {
            wx.showLoading({
              title: '更改中...',
            });
            util.putData("/atapi/delivery/process/priceIncomeMode", {
              id: that.data.currentId,
              type: 'month_knot_income',
              value: 0,
              'CO_ID': app.globalData.CO_ID,
              'user_id': app.globalData.user_id
            }, function (res, error) {
              wx.hideLoading();
              if (error) {
                wx.showToast({
                  title: res.data.data,
                  image: '/images/wrong.png',
                  duration: 3000
                });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: '已设：现结模式',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function () {
                      that.loadData();
                    }, 3000);
                  }
                });
              }
            });
          } else {
            wx.showToast({
              title: '已是现结模式',
              icon: 'success',
              duration: 2000
            });
          }
        }
      }
    })
  },
  //运费支出方式
  pricePayMode: function () {
    var that = this;
    that.setData({
      modalName: null
    })
    var order_list = that.data.order_list;
    var month_knot_pay = 1;
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == that.data.currentId) {
        month_knot_pay = order_list[i].month_knot_pay;
        break;
      }
    }
    wx.showModal({
      title: '运费支付方式',
      content: '更改运费支出方式，如果是现结，请确定已付款！',
      confirmText: '月结',
      cancelText: '现结',
      success(res) {
        if (res.confirm) {
          if (Number(month_knot_pay) != 1) {
            wx.showLoading({
              title: '更改中...',
            });
            util.putData("/atapi/delivery/process/priceIncomeMode", {
              id: that.data.currentId,
              type: 'month_knot_pay',
              value: 1,
              'CO_ID': app.globalData.CO_ID,
              'user_id': app.globalData.user_id
            }, function (res, error) {
              wx.hideLoading();
              if (error) {
                wx.showToast({
                  title: res.data.data,
                  image: '/images/wrong.png',
                  duration: 3000
                });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: '已设：月结模式',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function () {
                      that.loadData();
                    }, 3000);
                  }
                });
              }
            });
          } else {
            wx.showToast({
              title: '已是月结模式',
              icon: 'success',
              duration: 2000
            });
          }
        } else if (res.cancel) {
          if (Number(month_knot_pay) != 0) {
            wx.showLoading({
              title: '更改中...',
            });
            util.putData("/atapi/delivery/process/priceIncomeMode", {
              id: that.data.currentId,
              type: 'month_knot_pay',
              value: 0,
              'CO_ID': app.globalData.CO_ID,
              'user_id': app.globalData.user_id
            }, function (res, error) {
              wx.hideLoading();
              if (error) {
                wx.showToast({
                  title: res.data.data,
                  image: '/images/wrong.png',
                  duration: 3000
                });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: '已设：现结模式',
                  icon: 'success',
                  duration: 2000,
                  success: function () {
                    setTimeout(function () {
                      that.loadData();
                    }, 3000);
                  }
                });
              }
            });
          } else {
            wx.showToast({
              title: '已是现结模式',
              icon: 'success',
              duration: 2000
            });
          }
        }
      }
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  //查看运单单据图片
  deliveryDocument: function (e) {
    var that = this;
    var id = e.currentTarget.id;
    var order_list = that.data.order_list;
    var currentDelivery = {};
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == id) {
        currentDelivery = order_list[i]
      }
    }
    that.setData({
      modalName: 'deliveryDocument',
      currentDelivery: currentDelivery
    })
    util.postData("/zhc/datalist/getDataByListId",{
      "list_id": "63CD5292-35A1-47FD-9374-795099BFB9BB",
      "res": "",
      "page": {
        "size": 20,
        "current": 1,
        "orders": [
          {
            "column": "a.ADD_TIME",
            "asc": "false"
          }
        ]
      },
      "data": {
        "field": ""
      },
      "repeat_field": [],
      "condition": " a.delivery='"+currentDelivery.ID+"' ",
      "virtual_field": []
    }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        return false;
      }
      if (res.data.success && res.data?.result?.records.length > 0) {
        var count = res.data.result.total;
        var pageNumber = Math.ceil(count / that.data.pageSize);
          var data = res.data.result.records;
        var currentDeliveryPoint = [];
        for (var i = 0; i < data.length; i++) {
          var picture = String(data[i].picture).split(',');
          if (!!data[i].picture == false || data[i].picture == 'undefined') {
            picture = [];
          }
          currentDeliveryPoint.push({
            name: data[i].name,
            ID: data[i].ID,
            picture: picture
          })
        }
        that.setData({
          currentDeliveryPoint: currentDeliveryPoint
        })
        } else {
          
        }
    });
  },
  DelImg: function (e) {
    var that = this;
    var currentDelivery = that.data.currentDelivery;
    var index = e.currentTarget.dataset.index;
    console.log(index)
    var type = e.currentTarget.dataset.name;
    console.log(type)
    var imgList = [];
    var imgListCompress = [];
    if (type && type == 'tollfee') {
      imgList = currentDelivery.tollfee_docs;
      imgListCompress = currentDelivery.tollfee_docs_compress;
    }
    if (type && type == 'parkingfee') {
      imgList = currentDelivery.parkingfee_docs;
      imgListCompress = currentDelivery.parkingfee_docs_compress;
    }
    if (type && type == 'delivery_picture') {
      imgList = that.data.deliveryDocsImgList;
    }
    var url = imgList[index];
    var urlCompress = imgListCompress[index];
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除图片吗？',
      success(res) {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...'
          });
          if (url == '') {
            if (imgList.length == 1) {
              imgList = [];
              imgListCompress = [];
            } else {
              imgList.splice(index, 1);
              imgListCompress.splice(index, 1);
            }
            if (type && type == 'tollfee') {
              that.setData({
                'currentDelivery.tollfee_docs': imgList,
                'currentDelivery.tollfee_docs_compress': imgListCompress
              })
            }
            if (type && type == 'parkingfee') {
              that.setData({
                'currentDelivery.parkingfee_docs': imgList,
                'currentDelivery.parkingfee_docs_compress': imgListCompress
              })
            }
            if (type && type == 'delivery_picture') {
              that.setData({
                deliveryDocsImgList: imgList
              })
            }
            wx.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 2000,
              success: function () {

              }
            });
            return false;
          }
          if (imgList.length == 1) {
            imgList = [];
            imgListCompress = [];
          } else {
            imgList = util.arrayDeleteWithIndex(imgList, index, 1);
            imgListCompress = util.arrayDeleteWithIndex(imgListCompress, index, 1);
          }
          util.putData("/atapi/delivery/process/deleteFile", {
            url: url,
            delivery: currentDelivery.ID,
            urlCompress: urlCompress,
            imgListCompress: imgListCompress.join(','),
            imgList: imgList.join(','),
            type: type
          }, function (res, error) {
            console.log(res);
            console.log(error)
            wx.hideLoading();
            if (error) {
              wx.showToast({
                title: '删除失败',
                image: '/images/wrong.svg',
                duration: 2000
              });
              return false;
            }
            if (res.data.success) {
              if (type && type == 'tollfee') {
                that.setData({
                  'currentDelivery.tollfee_docs': imgList,
                  'currentDelivery.tollfee_docs_compress': imgListCompress
                })
              }
              if (type && type == 'parkingfee') {
                that.setData({
                  'currentDelivery.parkingfee_docs': imgList,
                  'currentDelivery.parkingfee_docs_compress': imgListCompress
                })
              }
              if (type && type == 'delivery_picture') {
                that.setData({
                  deliveryDocsImgList: imgList
                })
              }
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000,
                success: function () {

                }
              });
            }
          });
        }
      }
    });

  },
  confirmOnePriceDialogSetBtn: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.did;
    wx.showLoading({
      title: '设置中...',
    });
    var delivery = {},
      order_list = that.data.order_list;
    for (var i = 0; i < order_list.length; i++) {
      if (order_list[i].ID == id) {
        delivery = order_list[i];
        break;
      }
    }
    let target = {"driverPrice":that.data.onePrice}
    if(that.data.onePriceTypeOfPay === false){
      target = {"total_price":that.data.onePrice}
    }
    util.postData("/sys/form/commonUpdate",{
      "formId":"6E6999E1-1A6B-4F98-B1A4-A0A6BD77FAFC",
      "data":[{
          "dataId":id,
          "target":target
      }],
      "condition":""
      }, function (res, error) {
      console.log(res); console.log(error)
      wx.hideLoading();
      if (error) {
        return false;
      }
      if (res.data.success) {
        that.setData({
          dialog: false
        })
        wx.showToast({
          title: "设置一口价成功",
          icon: 'success',
          success: function () {
            setTimeout(function () {
              that.loadData();
            }, 3000);
          }
        });
      }else{
        wx.showToast({
          title: "设置失败",
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  cancelOnePriceDialogSetBtn: function () {
    this.setData({
      dialog: false
    })
  },
  confirmVehicleEmptyDialogSetBtn: function (e) {
    var that = this;

    wx.showLoading({
      title: '设置中...',
    });
    var driverPrice = that.data.vehicleEmptyPrice || '';
    if (that.data.vehicleEmptyPrice && isNaN(that.data.vehicleEmptyPrice) == true) {
      wx.showToast({
        title: '放空费输入有误',
        image: '/images/wrong.svg',
        duration: 2000
      })
      return false;
    }
    util.putData("/atapi/delivery/process/setVehicleEmpty", {
      id: that.data.currentId,
      driverPrice: driverPrice,
      user_id: app.globalData.user_id,
      unionid: app.globalData.unionid,
      CO_ID: app.globalData.CO_ID
    }, function (res, error) {
      if (res.data.success) {
        that.setData({
          vehicle_empty_dialog: false
        })
        wx.showToast({
          title: "车辆放空成功",
          icon: 'success',
          success: function () {
            setTimeout(function () {
              that.loadData();
            }, 3000);
          }
        });

      } else {
        wx.showToast({
          title: '车辆放空失败',
          image: '/images/wrong.svg',
          duration: 2000
        })
      }
      wx.hideLoading();
    });
  },
  cancelVehicleEmptyDialogSetBtn: function () {
    this.setData({
      vehicle_empty_dialog: false
    })
  },
  bindInput: function (e) {
    var that = this;
    var item = String(e.currentTarget.id),
      item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);

    var type = e.currentTarget.dataset.name;
    if (type) {
      var currentDelivery = that.data.currentDelivery;
      if (type == 'tollfee' && isNaN(e.detail.value) == false && currentDelivery.tollfee != e.detail.value) {
        util.getData("/atapi/delivery/process/changeFeeBySchedule", {
          id: currentDelivery.ID,
          type: type,
          fee: e.detail.value
        }, function (res, error) {
          if (res.data.success) {
            wx.showToast({
              title: '修改成功',
              icon: 'success',
              duration: 2000,
              success: function () {
                that.setData({
                  'currentDelivery.tollfee': e.detail.value
                })
              }
            })
          }
        });
      }
      if (type == 'parkingfee' && isNaN(e.detail.value) == false && currentDelivery.tollfee != e.detail.value) {
        util.putData("/atapi/delivery/process/changeFeeBySchedule", {
          id: currentDelivery.ID,
          type: type,
          fee: e.detail.value
        }, function (res, error) {
          if (res.data.success) {
            wx.showToast({
              title: '修改成功',
              icon: 'success',
              duration: 2000,
              success: function () {
                that.setData({
                  'currentDelivery.parkingfee': e.detail.value
                })
              }
            })
          } else {
            wx.showToast({
              title: '修改失败',
              image: '/images/wrong.svg',
              duration: 2000
            })
          }
        });
      }
    }
  },
  changeFee: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var value = e.detail.value;
    console.log(type + ':' + value)
    if (type) {
      var currentDelivery = that.data.currentDelivery;
      if (type == 'tollfee' && isNaN(value) == false && currentDelivery.tollfee != value) {
        util.putData("/atapi/delivery/process/changeFeeBySchedule", {
          id: currentDelivery.ID,
          type: type,
          fee: value
        }, function (res, error) {
          if (res.data.success) {
            wx.showToast({
              title: '修改成功',
              icon: 'success',
              duration: 2000,
              success: function () {
                that.setData({
                  'currentDelivery.tollfee': value
                })
              }
            })
          } else {
            wx.showToast({
              title: '修改失败',
              image: '/images/wrong.svg',
              duration: 2000
            })
          }
        });
      }
      if (type == 'parkingfee' && isNaN(value) == false && currentDelivery.tollfee != value) {
        util.putData("/atapi/delivery/process/changeFeeBySchedule", {
          id: currentDelivery.ID,
          type: type,
          fee: value
        }, function (res, error) {
          if (res.data.success) {
            wx.showToast({
              title: '修改成功',
              icon: 'success',
              duration: 2000,
              success: function () {
                that.setData({
                  'currentDelivery.parkingfee': value
                })
              }
            })
          } else {
            wx.showToast({
              title: '修改失败',
              image: '/images/wrong.svg',
              duration: 2000
            })
          }
        });
      }
      if (type == 'otherfee' && isNaN(value) == false && currentDelivery.otherfee != value) {
        util.putData("/atapi/delivery/process/changeFeeBySchedule", {
          id: currentDelivery.ID,
          type: type,
          fee: value
        }, function (res, error) {
          if (res.data.success) {
            wx.showToast({
              title: '修改成功',
              icon: 'success',
              duration: 2000,
              success: function () {
                that.setData({
                  'currentDelivery.otherfee': value
                })
              }
            })
          } else {
            wx.showToast({
              title: '修改失败',
              image: '/images/wrong.svg',
              duration: 2000
            })
          }
        });
      }
    }
  },
  previewImage: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.name;
    var current = e.currentTarget.dataset.url
    var currentDelivery = that.data.currentDelivery;
    var deliveryImageList = [];
    if (type && type == 'tollfee') {
      deliveryImageList = currentDelivery.tollfee_docs;
    }
    if (type && type == 'parkingfee') {
      deliveryImageList = currentDelivery.parkingfee_docs;
    }
    if (type && type == 'delivery_picture') {
      deliveryImageList = currentDelivery.delivery_picture;
    }
    console.log(current)
    console.log(deliveryImageList)
    wx.previewImage({
      current: current,
      urls: deliveryImageList
    })
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
    if (e.currentTarget.dataset.target == 'addLoadingGoods') {
      var id = e.currentTarget.id;
      var order_list = that.data.order_list;
      var currentDelivery = {};
      for (var i = 0; i < order_list.length; i++) {
        if (order_list[i].ID == id) {
          currentDelivery = order_list[i];
          break;
        }
      }
      that.setData({
        currentDelivery: currentDelivery,
        packages_expect: currentDelivery.packages_expect,
        packages: currentDelivery.packages || currentDelivery.packages_expect,
        volume: currentDelivery.volume || 0,
        weight: currentDelivery.weight || 0,
        goodsValue: currentDelivery.goodsValue || 0,
        unload_box: currentDelivery.unload_box || 0,
        back_box: currentDelivery.back_box || 0,
        return_package: currentDelivery.return_package || 0,
        goodsname: (currentDelivery.goodsname == 'undefined' || currentDelivery.goodsname == 'null') ? '' : currentDelivery.goodsname
      })
      this.getCurrentOrderGoods(currentDelivery)
    }
  },
  getCurrentOrderGoods: function (currentDelivery) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...',
    });
    util.getData("/atapi/delivery/process/getCurrentOrderGoodsData", {
      id: currentDelivery.ID
    }, function (res, error) {
      if (res.data.success) {
        var point_data = res.data.data;
        //装载数量处理
        var packageList = [];
        for (var i = 0; i < point_data.length; i++) {
          packageList.push({
            id: point_data[i].DID,
            name: point_data[i].name,
            shop: point_data[i].shop,
            package: point_data[i].package,
            unload_box: point_data[i].unload_box || 0,
            back_box: point_data[i].back_box || 0,
            return_package: point_data[i].return_package || 0,
            deliveryThirdParty_income: point_data[i].deliveryThirdParty_income || 0,
            deliveryThirdParty_pay: point_data[i].deliveryThirdParty_pay || 0,
            goodsInfo: (point_data[i].goodsInfo && point_data[i].goodsInfo != 'undefined') ? point_data[i].goodsInfo : '',
            remark: point_data[i].remark,
            loadingRule: []
          });
        };
        if (currentDelivery.loadingrule && currentDelivery.loadingrule != 'undefined') {
          for (var i = 0; i < packageList.length; i++) {
            var loadingRule = [],
              loading_rule = [];
            if (packageList[i].goodsInfo) {
              loading_rule = String(packageList[i].goodsInfo).split(",");
            } else {
              loading_rule = String(currentDelivery.loadingrule).split(",");
            }
            console.log(packageList[i].goodsInfo)
            console.log(loading_rule)
            if (loading_rule.length > 0) {
              for (var j = 0; j < loading_rule.length; j++) {
                var _item = String(loading_rule[j]).split("|");
                loadingRule.push({
                  "id": "LDR" + j,
                  "name": _item[0],
                  "ratio": _item[1],
                  "number": _item[2]
                });
              }
              packageList[i].loadingRule = loadingRule;
            }
          }
        }
        that.setData({
          packageList: packageList
        });
      } else {
        wx.showToast({
          title: '读取数据失败',
          image: '/images/wrong.svg',
          duration: 2000
        })
      }
      wx.hideLoading();
    });
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  bindLoadingInput: function (e) {
    var that = this;
    var packageList = that.data.packageList;
    var value = isNaN(e.detail.value) ? 0 : e.detail.value;
    var _id = String(e.currentTarget.id).split("_");
    var pid = _id[0];
    var id = _id[1];
    var packages = 0;
    for (var i = 0; i < packageList.length; i++) {
      var loadingRule = packageList[i].loadingRule,
        currentNumber = 0;
      if (packageList[i].id == pid) {
        var loading_rule = new Array();
        for (var j = 0; j < loadingRule.length; j++) {
          if (loadingRule[j].id == id) {
            loadingRule[j].number = value;
          }
          currentNumber += Number(loadingRule[j].number) * Number(loadingRule[j].ratio);
          loading_rule[j] = loadingRule[j].name + "|" + loadingRule[j].ratio + "|" + loadingRule[j].number;
        }
        packageList[i].loadingRule = loadingRule;
        packageList[i].package = currentNumber.toFixed(2);
        packageList[i].goodsInfo = loading_rule.join(",");
      }
      packages += Number(packageList[i].package);
    }

    that.setData({
      packageList: packageList,
      packages: packages.toFixed(2)
    });

    return value;
  },
  bindPackageInput: function (e) {
    var that = this;
    var packageList = that.data.packageList,
      packages = 0,
      unload_box = 0,
      back_box = 0,
      return_package = 0,
      deliveryThirdParty_income = 0,
      deliveryThirdParty_pay = 0;

    var value = isNaN(e.detail.value) ? 0 : e.detail.value;
    var id = String(e.currentTarget.id);
    var _id = id.split('_')

    for (var i = 0; i < packageList.length; i++) {
      if (packageList[i].id == id) {
        packageList[i].package = value;
      }
      if (packageList[i].id == _id[0] && _id[1] == 'unloadbox') {
        packageList[i].unload_box = value;
      }
      if (packageList[i].id == _id[0] && _id[1] == 'backbox') {
        packageList[i].back_box = value;
      }
      if (packageList[i].id == _id[0] && _id[1] == 'returnpackage') {
        packageList[i].return_package = value;
      }
      if (packageList[i].id == _id[0] && _id[1] == 'deliveryThirdPartyincome') {
        packageList[i].deliveryThirdParty_income = value;
      }
      if (packageList[i].id == _id[0] && _id[1] == 'deliveryThirdPartypay') {
        packageList[i].deliveryThirdParty_pay = value;
      }
      packages += Number(packageList[i].package || 0);
      unload_box += Number(packageList[i].unload_box || 0);
      back_box += Number(packageList[i].back_box || 0);
      return_package += Number(packageList[i].return_package || 0);
      deliveryThirdParty_income += Number(packageList[i].deliveryThirdParty_income || 0);
      deliveryThirdParty_pay += Number(packageList[i].deliveryThirdParty_pay || 0);
    }

    that.setData({
      packageList: packageList,
      packages: packages.toFixed(2),
      unload_box: unload_box.toFixed(2),
      back_box: back_box.toFixed(2),
      return_package: return_package.toFixed(2),
      deliveryThirdParty_income: deliveryThirdParty_income.toFixed(2),
      deliveryThirdParty_pay: deliveryThirdParty_pay.toFixed(2)
    });

    return value;
  },
  bindGoodsInfoInput: function (e) {
    var that = this;
    var packageList = that.data.packageList;

    var value = e.detail.value;
    var id_goodsInfo = String(e.currentTarget.id).replace("_goodsInfo", "");
    var id_remark = String(e.currentTarget.id).replace("_remark", "");

    for (var i = 0; i < packageList.length; i++) {
      if (packageList[i].id == id_goodsInfo) {
        packageList[i].goodsInfo = value;
      }
      if (packageList[i].id == id_remark) {
        packageList[i].remark = value;
      }
    }

    that.setData({
      packageList: packageList
    });

    return value;
  },
  loading_form_ok: function () {
    var that = this;
    if (!that.data.packages || that.data.packages == '') {
      wx.showToast({
        title: '请输入箱框总数',
        image: '/images/wrong.png',
        duration: 3000
      });
      //that.setData({ "packages_expect": 0 });
      return false;
    }
    util.putData("deliveryPackage", {
      orderId: that.data.currentDelivery.ID,
      goodsname: that.data.goodsname || '',
      packages_expect: that.data.packages_expect,
      packages: that.data.packages,
      volume: that.data.volume || 0,
      weight: that.data.weight || 0,
      unload_box: that.data.unload_box || 0,
      back_box: that.data.back_box || 0,
      return_package: that.data.return_package || 0,
      goodsValue: that.data.goodsValue || 0,
      packageList: JSON.stringify(that.data.packageList),
      user_id: app.globalData.user_id,
      CO_ID: app.globalData.CO_ID
    }, function (res, error) {
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: '设置成功',
          icon: 'success',
          duration: 2000,
          success: function () {
            that.hideModal();
            setTimeout(function () {
              that.loadData();
            }, 2000);
          }
        })
      } else {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.png',
          duration: 3000
        });
      }
    });
  },
  //接驳费
  submitDeliveryThirdPartyFee: function () {
    var that = this;
    var deliveryThirdParty_income = that.data.deliveryThirdParty_income;
    var deliveryThirdParty_pay = that.data.deliveryThirdParty_pay;
    // if (isNaN(Number(deliveryThirdParty_income)) == true || deliveryThirdParty_income == 0) {
    //   wx.showToast({ title: '请填写费用金额', image: '/images/wrong.svg', duration: 2000 });
    //   return false;
    // }
    // if (!deliveryThirdParty_pay) {
    //   wx.showToast({ title: '请填写费用名目', image: '/images/wrong.svg', duration: 2000 });
    //   return false;
    // }

    wx.showLoading({
      title: '提交中...'
    });
    util.putData("/atapi/delivery/process/deliveryThirdPartyFee", {
      id: that.data.currentId,
      deliveryThirdParty_income: deliveryThirdParty_income,
      deliveryThirdParty_pay: deliveryThirdParty_pay,
      packageList: JSON.stringify(that.data.packageList),
      user_id: app.globalData.user_id,
      CO_ID: app.globalData.CO_ID
    }, function (res, error) {
      console.log(res);
      console.log(error)
      wx.hideLoading();
      if (error) {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
        return false;
      }
      if (res.data.success) {
        wx.showToast({
          title: res.data.data,
          icon: 'success',
          duration: 2000
        });
        that.hideModal();
        setTimeout(function () {
          that.loadData();
        }, 2000);
      } else {
        wx.showToast({
          title: res.data.data,
          image: '/images/wrong.svg',
          duration: 2000
        });
      }
    });
  },
})